<!--
 * @author luguoxiang
 * @date 2022/9/17
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
-->
<template>
  <edit-container ref="containerRef" header="分配角色" width="600px" @confirm="submit">
    <lg-biz-tree :data="roleApi.query" fields="id,name,parentId">
      <template #default="{ options }">
        <t-tree v-model="joinIds" :data="options" hover expand-all :expand-level="1" checkable></t-tree>
      </template>
    </lg-biz-tree>
  </edit-container>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { EditContainer } from '@/components';
import { LgBizTree, notEmpty } from '@/soar';
import api from './api';
import roleApi from '../role/api';

const emits = defineEmits(['ok']);

const containerRef = ref();
const joinIds = ref([]);
const mainIds = ref([]);
const loading = ref(true);

function submit() {
  api
    .setRoleIds({ aids: mainIds.value, bids: joinIds.value })
    .then(() => {
      containerRef.value.close();
      emits('ok');
    })
    .finally(() => {
      loading.value = false;
    });
  loading.value = true;
}

defineExpose({
  open(ids) {
    if (Array.isArray(ids)) {
      notEmpty(ids, '请选择至少一条数据');
      joinIds.value = [];
    } else {
      api.getRoleIds(ids).then((res) => {
        joinIds.value = res;
      });
      ids = [ids];
    }
    mainIds.value = ids;
    containerRef.value.open();
  },
});
</script>
